package cn.dcw.pethome.org.controcller;

import cn.dcw.pethome.basic.util.AjaxResult;
import cn.dcw.pethome.basic.util.PageList;
import cn.dcw.pethome.org.domain.Department;
import cn.dcw.pethome.org.query.DepartmentQuery;
import cn.dcw.pethome.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.lang.reflect.Array;
import java.util.List;

/**
 * 部门接口
 * restful风格
 */
@RestController
@RequestMapping("/dept")
@Api(tags = "部门接口",description = "部门接口详细描述")
public class DepartmentController {
    @Autowired
    private IDepartmentService service;
    /**
     * 添加/修改
     * RequestBody  将前端传递过来的json格式的数据转换为对象
     */
    @PutMapping
    @ApiOperation(value = "部门添加或修改",notes = "如果有id就是修改否则就是添加")
    public AjaxResult addOrUpdate(@RequestBody Department department){
        System.out.println(department);
        try {
            //判断是添加还是修改
            if(department.getId()==null){//添加
                service.add(department);
            }else {//修改
                service.update(department);
            }
            //返回成功结果
            return new AjaxResult(true, "操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            //返回失败的结果
            return new AjaxResult(false, "操作失败");
        }
    }
    /**
     * 删除
     * @PathVariable  接收id数据
     *
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "部门删除",notes = "通过输入的id删除数据")
    public AjaxResult del(@PathVariable("id") Long id){
        try {
            service.delete(id);
            return new AjaxResult(true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "删除失败");
        }
    }

    /**
     * 批量删除
     * PatchMapping  批量操作注解
     */
    @PatchMapping
    @ApiOperation(value = "批量删除",notes = "通过输入的id删除数据")
    public AjaxResult batchDel(@RequestBody Long[] ids){
        try {
            service.batchDel(ids);
            return new AjaxResult(true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "删除失败");
        }
    }
    /*
    查询所有数据
     */
    @GetMapping()
    @ApiOperation(value = "查询所有部门信息",notes = "查询所有部门信息")
    public List<Department> findAllById(){
       return service.findAll();
    }
    /**
     * 分页查询
     */
    @PostMapping
    @ApiOperation(value = "分页",notes = "分页查询")
    public PageList<Department> queryPage(@RequestBody DepartmentQuery query){
        return service.pageData(query);
    }
    //二级联动查询父级部门
    @GetMapping("/tree")
    public List<Department> getTree(){
        return service.getTree();
    }
}
